
from flask import current_app
from admin_models.model_public import BackgroundImage, BottomInfo, Nav, policyFiles
from utils.extensions import db
from utils.tool import setResponseData


def getNavList():
    try:
        nav_items = Nav.query.order_by(Nav.sort).all()

        response_data = [item.getList() for item in nav_items]

        return setResponseData('10000000', 'success', response_data)

    except Exception as e:
        # 记录或处理异常
        current_app.logger.error(f"数据库操作时发生错误：{e}")
        return setResponseData('00000000', 'fail', "数据库访问错误")


def addNewNav(data):
    try:
        session = db.session

        # 调用add_new_record方法添加新记录
        new_record = Nav.add(Nav, data, session)

        return setResponseData('10000000', 'success', new_record.id)

    except Exception as e:
        # 发生异常时回滚事务
        db.session.rollback()
        current_app.logger.error(f"添加菜单时发生错误：{e}")
        return setResponseData('00000000', 'fail', "添加失败")

    finally:
        # 不论成功或失败，最终关闭数据库会话
        db.session.close()


def updateNavById(id, data):
    try:
        session = db.session

        Nav.update(Nav, id, data, session)

        return setResponseData('10000000', 'success', '')

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"更新导航记录时发生错误：{e}")
        return setResponseData('00000000', 'fail', "更新失败")

    finally:
        # 关闭数据库会话
        db.session.close()


def deleteNavById(id):
    try:
        session = db.session

        # 调用delete_by_id方法删除指定ID的记录
        success = Nav.delete(Nav, id, session)

        if success:
            return setResponseData('10000000', 'success', '')
        else:
            return setResponseData('10000000', 'success', "删除失败，未找到指定ID的记录")

    except Exception as e:
        # 发生异常时回滚事务
        db.session.rollback()
        current_app.logger.error("删除导航记录时发生错误：{e}")
        return setResponseData('00000000', 'fail', "删除失败")

    finally:
        # 不论成功或失败，最终关闭数据库会话
        db.session.close()


def getPolicyFilesList(area=None, major1=None, major2=None):
    try:
        session = db.session
        list = policyFiles.getList( session, area, major1, major2)

        return setResponseData('10000000', 'success', list)

    except Exception as e:
        # 记录或处理异常
        current_app.logger.error(f"数据库操作时发生错误：{e}")
        return setResponseData('00000000', 'fail', "数据库访问错误")


def getPolicyFilesListPage(page=1, per_page=10, area=None, major1=None, major2=None, keyword=None):
    try:
        session = db.session
        result = policyFiles.getPage(session, page, per_page, area, major1, major2, keyword)

        return setResponseData('10000000', 'success', result)

    except Exception as e:
        # 记录或处理异常
        current_app.logger.error(f"获取政策文件分页列表时发生错误：{e}")
        return setResponseData('00000000', 'fail', "获取政策文件分页列表失败")

    finally:
        db.session.close()


def addPolicyFile(data):
    try:
        session = db.session

        # 调用add_new_record方法添加新记录
        new_record = policyFiles.add( data, session)

        return setResponseData('10000000', 'success', new_record.id)

    except Exception as e:
        # 发生异常时回滚事务
        db.session.rollback()
        current_app.logger.error(f"添加政策文件时发生错误：{e}")
        return setResponseData('00000000', 'fail', "添加失败")

    finally:
        # 不论成功或失败，最终关闭数据库会话
        db.session.close()


def updatePolicyFileById(id, data):
    try:
        session = db.session

        policyFiles.update( id, data, session)

        return setResponseData('10000000', 'success', '')

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"更新政策文件时发生错误：{e}")
        return setResponseData('00000000', 'fail', "更新失败")

    finally:
        # 关闭数据库会话
        db.session.close()

def deletePolicyFile(id):
    try:
        session = db.session

        # 调用delete方法删除记录
        result = policyFiles.delete(id, session)

        if result:
            return setResponseData('10000000', 'success', '')
        else:
            return setResponseData('00000000', 'fail', '未找到要删除的政策文件')

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"删除政策文件时发生错误：{e}")
        return setResponseData('00000000', 'fail', "删除政策文件失败")

    finally:
        # 关闭数据库会话
        db.session.close()


def getBottomInfo(id):
    try:
        session = db.session
        bottom_info = BottomInfo.get_by_id(id, session)
        
        if bottom_info:
            return setResponseData('10000000', 'success', bottom_info.to_dict())
        else:
            return setResponseData('00000000', 'fail', "未找到底部信息")

    except Exception as e:
        current_app.logger.error(f"获取底部信息时发生错误：{e}")
        return setResponseData('00000000', 'fail', "获取底部信息失败")

    finally:
        db.session.close()

def updateBottomInfo(id, data):
    try:
        session = db.session

        BottomInfo.update(id, data, session)

        return setResponseData('10000000', 'success', '')

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"更新底部信息时发生错误：{e}")
        return setResponseData('00000000', 'fail', "更新底部信息失败")

    finally:
        db.session.close()
def addBackgroundImage(data):
    try:
        session = db.session
        new_image = BackgroundImage.add(data, session)
        return setResponseData('10000000', 'success', new_image.to_dict())

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"添加背景图片时发生错误：{e}")
        return setResponseData('00000000', 'fail', "添加背景图片失败")

    finally:
        db.session.close()


def getBackgroundImage():
    try:
        session = db.session
        active_image = BackgroundImage.get_active_image(session)
        
        if active_image:
            return setResponseData('10000000', 'success', active_image.to_dict())
        else:
            return setResponseData('00000000', 'fail', "未找到活动背景图片")

    except Exception as e:
        current_app.logger.error(f"获取背景图片时发生错误：{e}")
        return setResponseData('00000000', 'fail', "获取背景图片失败")

    finally:
        db.session.close()

def setBackgroundImageActiveStatus(id, is_active):
    try:
        session = db.session
        success = BackgroundImage.set_active(id, is_active, session)
        
        if success:
            return setResponseData('10000000', 'success', '')
        else:
            return setResponseData('00000000', 'fail', "设置背景图片活动状态失败")

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"设置背景图片活动状态时发生错误：{e}")
        return setResponseData('00000000', 'fail', "设置背景图片活动状态失败")

    finally:
        db.session.close()


def getAllBackgroundImages():
    try:
        session = db.session
        all_images = BackgroundImage.get_all_images(session)
        
        images_list = [image.to_dict() for image in all_images]
        return setResponseData('10000000', 'success', images_list)

    except Exception as e:
        current_app.logger.error(f"获取所有背景图片时发生错误：{e}")
        return setResponseData('00000000', 'fail', "获取所有背景图片失败")

    finally:
        db.session.close()

def updateBackgroundImage(id, data):
    try:
        session = db.session
        BackgroundImage.update(id, data, session)
        return setResponseData('10000000', 'success', '')

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"更新背景图片时发生错误：{e}")
        return setResponseData('00000000', 'fail', "更新背景图片失败")

    finally:
        db.session.close()

def deleteBackgroundImage(id):
    try:
        session = db.session
        success = BackgroundImage.delete(id, session)
        
        if success:
            return setResponseData('10000000', 'success', '')
        else:
            return setResponseData('00000000', 'fail', "删除背景图片失败")

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"删除背景图片时发生错误：{e}")
        return setResponseData('00000000', 'fail', "删除背景图片失败")

    finally:
        db.session.close()

